<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkAgent\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\ChatTool\Contract\ChatToolContract;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\User\Logic\Traits\UserTrait;
use MoChat\App\Utils\Url;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 企业应用 - 创建提交.
 * @author
 *
 * Class Info.
 * @Controller
 */
class Info extends AbstractAction
{
    use ValidateSceneTrait;
    use UserTrait;

    /**
     * @Inject
     * @var WorkAgentContract
     */
    protected $workAgentService;

    /**
     * @Inject
     * @var ChatToolContract
     */
    protected $chatToolService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/agent/info", methods="get")
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 参数验证
        $params['type'] = $this->request->input('type'); // 1:配置客户画像和群画像,2:自建应用,3:素材库
        $params['corpId'] = user()['corpIds'][0];
        $this->validated($params);

        $agent = $this->workAgentService->getWorkAgentByCorpIdType((int) $params['corpId'], (int) $params['type'], ['id', 'corp_id', 'wx_agent_id', 'wx_secret', 'customized_publish_status']);

        if (empty($agent)) {
            return [
                'publishStatus' => 0,
                'sidebar' => [],
                'workbench' => '',
            ];
        }
        $agentId = $agent['id'];
        $agent['publishStatus'] = $agent['customizedPublishStatus'];
        unset($agent['customizedPublishStatus']);
        $agent['sidebar'] = $this->getChatTool($agentId);
        $agent['workbench'] = Url::getWorkbenchBaseUrl() . '/?agentId=' . $agentId;
        return $agent;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => '类型 必填',
        ];
    }

    private function getChatTool(int $agentId): array
    {
        $chatTools = $this->chatToolService->getChatToolsByStatus(1);
        if (empty($chatTools)) {
            return $chatTools;
        }

        $newChatTools = [];
        foreach ($chatTools as $chatTool) {
            $url = "/{$chatTool['pageFlag']}?agentId={$agentId}";
            if (isset($chatTool['pageType']) && $chatTool['pageType'] === 2) {
                $url = "{$url}&id={$chatTool['id']}";
            }

            $newChatTools[] = [
                'name' => $chatTool['pageName'],
                'url' => Url::getSidebarBaseUrl() . $url,
            ];
        }

        return $newChatTools;
    }
}
